<template>
  <div class="about">
    <!-- 树形选择器 -->
    <el-select :clearable="clearable" v-model="selectedValue" placeholder="请选择" ref="selectTree" @visible-change="handleVisibleChange" @clear="handleClear">
      <el-option :value="selectedValue" hidden/>
      <el-tree
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        empty-text="没有可选数据"
        accordion
        :indent="20"
        :default-expand-all="defaultExpandAll"
        :highlight-current="true"
        @node-click="handleNodeClick"
      />
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'SelectedTree',
  props: {
    // 树形结构数据
    treeData: {
      type: Array,
      required: true
    },
    // 默认属性配置
    defaultProps: {
      type: Object,
      default() {
        return {
          children: 'children',
          label: 'label'
        }
      }
    },
    // 是否默认展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    // 初始选中值
    value: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedValue: this.value // 使用 prop 设置初始值
    }
  },
  watch: {
    value(newValue) {
      this.selectedValue = newValue
    }
  },
  methods: {
    handleNodeClick(data) {
      this.selectedValue = data.label
      this.$emit('input', data.id)
      this.$emit('node-click', data)
      this.$refs.selectTree.blur() // 隐藏下拉框
    },
    handleVisibleChange(visible) {
      if (!visible) {
        // 当下拉框隐藏时触发
        this.$emit('close')
      }
    },
    handleClear() {
      this.$emit('clear')
    }
  }
}
</script>

